package com.vm.myview;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
//import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;

import com.nineoldandroids.view.ViewHelper;
import com.vm.utils.ScreenUtils;
import com.wwtscapp.apk.R;

public class SlidingMenu extends HorizontalScrollView {
	/**
	 * 屏幕宽度
	 */
	private int mScreenWidth;
	/**
	 * dp
	 */
	private int mMenuRightPadding;
	/**
	 * 菜单的宽度
	 */
	private int mMenuWidth;
	private int mHalfMenuWidth;

	private boolean isOpen;

	private boolean once;

	private ViewGroup mMenu;
	private ViewGroup mContent;

	public SlidingMenu(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
		// mGestureDetector = new GestureDetector(context, new
		// YScrollDetector());

	}

	public SlidingMenu(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		mScreenWidth = ScreenUtils.getScreenWidth(context);

		TypedArray a = context.getTheme().obtainStyledAttributes(attrs,
				R.styleable.SlidingMenu, defStyle, 0);
		int n = a.getIndexCount();
		for (int i = 0; i < n; i++) {
			int attr = a.getIndex(i);
			switch (attr) {
			case R.styleable.SlidingMenu_rightPadding:
				// 默认50
				mMenuRightPadding = a.getDimensionPixelSize(attr,
						(int) TypedValue.applyDimension(
								TypedValue.COMPLEX_UNIT_DIP, 50f,
								getResources().getDisplayMetrics()));// 默认为10DP
				break;
			}
		}

		// mGestureDetector = new GestureDetector(context, new
		// YScrollDetector());
		a.recycle();
	}

	// private GestureDetector mGestureDetector;
	//
	// @Override
	// public boolean onInterceptTouchEvent(MotionEvent ev) {
	//
	// return isOpen ? super.onInterceptTouchEvent(ev) : super
	// .onInterceptTouchEvent(ev) && mGestureDetector.onTouchEvent(ev);
	// }

	public SlidingMenu(Context context) {
		this(context, null, 0);
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		/**
		 * 显示的设置一个宽度
		 */
		if (!once) {
			LinearLayout wrapper = (LinearLayout) getChildAt(0);
			mMenu = (ViewGroup) wrapper.getChildAt(0);
			mContent = (ViewGroup) wrapper.getChildAt(1);

			mMenuWidth = mScreenWidth - mMenuRightPadding;
			mHalfMenuWidth = mMenuWidth / 2;
			mMenu.getLayoutParams().width = mMenuWidth;
			mContent.getLayoutParams().width = mScreenWidth;

		}
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);

	}

	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
		super.onLayout(changed, l, t, r, b);
		if (changed) {
			// 将菜单隐藏
			this.scrollTo(mMenuWidth, 0);
			once = true;
		}
	}

	float x_temp01 = 0.0f;
	float y_temp01 = 0.0f;
	float x_temp02 = 0.0f;
	float y_temp02 = 0.0f;
	float x_scroll = 0.0f;
	float y_scroll = 0.0f;

	@SuppressLint("ClickableViewAccessibility")
	@Override
	public boolean onTouchEvent(MotionEvent ev) {
		createVelocityTracker(ev);
		float x = ev.getRawX();
		float y = ev.getRawY();
		int action = ev.getAction();
		switch (action) {
		case MotionEvent.ACTION_DOWN: {
			x_temp01 = x;
			y_temp01 = y;
			break;
		}

		case MotionEvent.ACTION_MOVE: {
			if (x_temp01 == 0 && y_temp01 == 0) {
				x_temp01 = x;
				y_temp01 = y;
			}
			break;
		}
		// Up时，进行判断，如果显示区域大于菜单宽度一半则完全显示，否则隐藏
		case MotionEvent.ACTION_UP:
			x_temp02 = x;
			y_temp02 = y;

			x_scroll = x_temp02 - x_temp01;
			y_scroll = Math.abs(y_temp02 - y_temp01);

			if (!isOpen) {
				Log.i("isOpen", "" + isOpen);
				if (x_temp01 != 0 && y_temp01 != 0)//
				{

					// Log.i("X移动的距离：", "" + x_scroll);
					// Log.i("Y移动的距离：", "" + y_scroll);
					if (x_scroll < 0) {
						this.smoothScrollTo(mMenuWidth, 0);
						isOpen = false;
						// return super.onTouchEvent(ev);
					} else {
						if (x_scroll > y_scroll * 1.5) {
							// Log.i("右滑", "弹出菜单");
							this.smoothScrollTo(0, 0);
							isOpen = true;
						} else {
							this.smoothScrollTo(mMenuWidth, 0);
							isOpen = false;
						}
					}

				} else {
					int scrollX = getScrollX();
					Log.i("scrollX", "scrollX:" + scrollX);
					if (scrollX > mHalfMenuWidth) {
						this.smoothScrollTo(mMenuWidth, 0);
						isOpen = false;
					} else {
						this.smoothScrollTo(0, 0);
						isOpen = true;
					}
				}
			} else {
				Log.i("isOpen", "" + isOpen);

				if (x_temp01 > mMenuWidth || x_temp02 > mMenuWidth) {
					this.smoothScrollTo(mMenuWidth, 0);
					isOpen = false;
				} else {
					if (x_temp01 != 0 && y_temp01 != 0)//
					{

						// Log.i("X1：", "" + x_temp01);
						// Log.i("X2：", "" + x_temp02);
						// Log.i("Y1：", "" + y_temp01);
						// Log.i("Y2：", "" + y_temp02);
						// Log.i("Y移动的距离：", "" + y_scroll);
						// Log.i("X移动的距离：", "" + x_scroll);
						// Log.i("Y移动的距离：", "" + y_scroll);
						if (x_scroll > 0) {
							this.smoothScrollTo(0, 0);
							isOpen = true;
							// return super.onTouchEvent(ev);
						} else {

							if (Math.abs(x_scroll) > y_scroll * 1.5) {
								// Log.i("左滑", "隐藏菜单");
								this.smoothScrollTo(mMenuWidth, 0);
								isOpen = false;
							} else {
								this.smoothScrollTo(0, 0);
								isOpen = true;
							}
						}

					}

				}

			}

			x_temp01 = 0.0f;
			y_temp01 = 0.0f;

			x_temp02 = 0.0f;
			y_temp02 = 0.0f;

			return true;
		}
		return super.onTouchEvent(ev);
		// return false;
	}

	/**
	 * 打开菜单
	 */
	public void openMenu() {
		if (isOpen)
			return;
		this.smoothScrollTo(0, 0);
		isOpen = true;
	}

	/**
	 * 关闭菜单
	 */
	public void closeMenu() {
		if (isOpen) {
			this.smoothScrollTo(mMenuWidth, 0);
			isOpen = false;
		}
	}

	/**
	 * 切换菜单状态
	 */
	public void toggle() {
		if (isOpen) {
			closeMenu();
		} else {
			openMenu();
		}
	}

	@Override
	protected void onScrollChanged(int l, int t, int oldl, int oldt) {
		super.onScrollChanged(l, t, oldl, oldt);
		float scale = l * 1.0f / mMenuWidth;
		float leftScale = 1 - 0.3f * scale;
		float rightScale = 0.8f + scale * 0.2f;

		ViewHelper.setScaleX(mMenu, leftScale);
		ViewHelper.setScaleY(mMenu, leftScale);
		ViewHelper.setAlpha(mMenu, 0.6f + 0.4f * (1 - scale));
		ViewHelper.setTranslationX(mMenu, mMenuWidth * scale * 0.7f);

		ViewHelper.setPivotX(mContent, 0);
		ViewHelper.setPivotY(mContent, mContent.getHeight() / 2);
		ViewHelper.setScaleX(mContent, rightScale);
		ViewHelper.setScaleY(mContent, rightScale);

	}

	/**
	 * 用于计算手指滑动的速度。
	 */
	private VelocityTracker mVelocityTracker;

	/**
	 * 创建VelocityTracker对象，并将触摸事件加入到VelocityTracker当中。
	 * 
	 * @param event
	 *            右侧布局监听控件的滑动事件
	 */
	@SuppressLint("Recycle")
	private void createVelocityTracker(MotionEvent event) {
		if (mVelocityTracker == null) {
			mVelocityTracker = VelocityTracker.obtain();
		}
		mVelocityTracker.addMovement(event);
	}

	/**
	 * 获取手指在右侧布局的监听View上的滑动速度。
	 * 
	 * @return 滑动速度，以每秒钟移动了多少像素值为单位。
	 */
	@SuppressWarnings("unused")
	private int getScrollVelocity() {
		mVelocityTracker.computeCurrentVelocity(1000);
		int velocity = (int) mVelocityTracker.getXVelocity();
		return Math.abs(velocity);
	}

}

class YScrollDetector extends SimpleOnGestureListener {

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		// 如果我们滚动更接近水平方向,返回false,让子视图来处理它
		return (Math.abs(distanceY) > Math.abs(distanceX));
	}
}
